package ar.edu.itba.it.paw.services.impl;

import java.util.List;

import ar.edu.itba.it.paw.dao.OpinionDAO;
import ar.edu.itba.it.paw.dao.UserDAO;
import ar.edu.itba.it.paw.dao.impl.DatabaseOpinionDAO;
import ar.edu.itba.it.paw.dao.impl.DatabaseUserDAO;
import ar.edu.itba.it.paw.domain.Opinion;
import ar.edu.itba.it.paw.domain.User;
import ar.edu.itba.it.paw.domain.exceptions.RegisteredMailException;
import ar.edu.itba.it.paw.domain.exceptions.RegisteredUsernameException;
import ar.edu.itba.it.paw.services.UserServices;


public class UserServicesImpl implements UserServices {

	private static UserServicesImpl instance;
	
	/*solo lo voy a usar internamente, por eso no necesito getter*/
	private static UserDAO user_dao ;
	private static OpinionDAO opinion_dao;
	
	public static synchronized UserServicesImpl getInstance(){
		if(instance == null){
			instance = new UserServicesImpl();
			/*Al crear la instancia de UserServices guardo la instancia del DAO en una variable para poder
			 * accederla directamente cada vez que la necesito*/
			user_dao = DatabaseUserDAO.getInstance();
			opinion_dao = DatabaseOpinionDAO.getInstance();
		}
		return instance;
	}
	
	public void addUser(User user) throws RegisteredUsernameException, RegisteredMailException{
		/*El usuario ya viene validado por la clase*/

		if(!user_dao.existsUser(user)){
			user_dao.addUser(user);
		}
		else{
			if(user_dao.existsMail(user.getMail())){
				throw new RegisteredMailException();
			}
			if(user_dao.getUser(user.getUsername()) != null){
				throw new RegisteredUsernameException();
			}
		}
	}
	
	/*Devuelve null si el String del parametro es null y si no hay resultados de la query lanza  
	 * UnknownUserException*/
	public User getUser(String username){
		if(username != null && !username.equals(""))
			return user_dao.getUser(username);
		else
			return null;
	}
	
	/*lanzar UnknownUserException*/
	public User getUser(int id) {
		if(id > 0)
			return user_dao.getUser(id);
		else
			return null;
	}
	
	
	public boolean authenticate(String username, String password){
		User user;
		if((user = user_dao.getUser(username)) != null){
			if(user.getPassword().equals(password)){
				return true;
			}
		}
		return false;
	}

	public void addOpinion(Opinion opinion){
		if(opinion != null){
			opinion_dao.addOpinion(opinion);
		}
	}

	@Override
	public List<Opinion> getAllOpinions() {
		return opinion_dao.getAllOpinions();
		
	}

}
